'use strict'
import DyRoom from './dy/dyroom'
import PandaRoom from './panda/pandaroom'
import EventEmitter from './EventEmitter'
export default class RoomManage extends EventEmitter {
  constructor () {
    super()
    this.rooms = new Map()
  }
  addRoom (platform, roomId, fn) {
    if (!fn && typeof fn !== 'function') {
      return
    }
    if (this.rooms.has(this._getKey(platform, roomId))) {
      fn(-2)
      return
    }
    let room = null
    switch (platform) {
      case 'dy':
        room = new DyRoom(roomId)
        room.on('init', (id) => {
          if (id !== '-1') {
            this.rooms.set(this._getKey('dy', id), room)
            fn(0, room.data)
          } else {
            fn(-1)
          }
        })
        break
      case 'panda':
        room = new PandaRoom(roomId)
        room.on('init', (id) => {
          if (id) {
            this.rooms.set(this._getKey('panda', id), room)
            fn(0, room.data)
          } else {
            fn(-1)
          }
        })
        break
    }
  }
  remove (platform, roomId) {
    let key = this._getKey(platform, roomId)
    let room = this.rooms.get(key)
    if (room) {
      room.remove()
      this.rooms.delete(key)
    }
  }
  getRank (key, field) {
    var room = this.rooms.get(key)
    if (room) {
      return room.data.filter(field)
    }
    return null
  }
  getRooms () {
    let rooms = Array.from(this.rooms).map((room) => {
      return room[1]
    })
    return Array.from(rooms).map((room) => {
      return room.data
    })
  }
  getRoom (platform, roomId) {
    let key = this._getKey(platform, roomId)
    return this.rooms.get(key)
  }
  hasRoom (platform, roomId) {
    let key = this._getKey(platform, roomId)
    return this.rooms.has(key)
  }
  getGift (key) {
    let room = this.rooms.get(key)
    if (room) {
      let gift = room.data.gift
      var gifts = []
      for (var _key in gift) {
        if (gift.hasOwnProperty(_key)) {
          gifts.push({
            text: gift[_key].name + '总榜',
            value: gift[_key].id
          })
        }
      }
      return gifts
    }
    return null
  }
  getOnLineChart (key) {
    return this._getChart(key, 'getOnLineChart')
  }
  getContrastChart (key) {
    return this._getChart(key, 'getContrastChart')
  }
  getGiftChart (key) {
    return this._getChart(key, 'getGiftChart')
  }
  _getChart (key, fnName) {
    let room = this.rooms.get(key)
    if (room) {
      return room.data[fnName]()
    }
  }
  _getKey (platform, roomId) {
    return platform.concat('_').concat(roomId)
  }
}
